import Joi from "joi";
import { errorResponse } from './../../utils/errors.js';

console.log('全局错误处理中间件加载成功')
export function errorHandler(err, req, res, next) {
  console.error('[Error]', err);
  
  // 处理Joi验证错误
  if (err instanceof Joi.ValidationError) {
    return errorResponse(res, {
      statusCode: 400,
      code: 'VALIDATION_ERROR',
      message: '数据验证失败',
      details: err.details.map(d => d.message)
    });
  }
  
  // 处理自定义错误
  if (err.statusCode) {
    return errorResponse(res, err);
  }
  
  // 处理其他未知错误
  errorResponse(res, {
    statusCode: 500,
    code: 'INTERNAL_ERROR',
    message: 'Internal Server Error'
  });
}